package demo.selenium.framework;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;

import com.thoughtworks.selenium.SeleneseTestCase;

import demo.util.BaseUtils;
import demo.util.Console;

public abstract class BaseSeleniumJUnitTestCase extends SeleneseTestCase {

    protected static final int WAITING_DELAY_SEC = 1;

    protected static Console console = BaseUtils.getConsole();

    protected Map<String, String> locatorMap = new HashMap<String, String>();

    @BeforeClass
    public static void init() {

        // connect server
        // connectSeleniumServer();

        // load properties
        // loadProperties();

        // configuration
        // config();
    }

    @AfterClass
    public static void end() {
        manualBreak();
    }

    static void config() {
        // useCssSelector(true);
        // useTelluriumEngine(false);
        // useTelluriumApi(false);
        // useTrace(false);
        // useEngineLog(true);
    }

    static void loadProperties() {
        BaseUtils.loadProperties();
    }

    protected static String getProperty(String key) {
        return BaseUtils.getProperty(key);
    }

    protected static void waitingDelay() {
        // pauseSec(WAITING_DELAY_SEC);
    }

    protected void pauseSec(int seconds) {
        pause(seconds * 1000);
    }

    protected static <T> T cast(Object obj) {
        return BaseUtils.cast(obj);
    }

    protected static void manualBreak() {
        String cmd = console.readLine();
        if (StringUtils.endsWithIgnoreCase(cmd, "exit") || StringUtils.endsWithIgnoreCase(cmd, "quit")) {
            throw new RuntimeException("User has stopped this operation.");
        }
    }

    protected static String getLocator(String selector) {
        return "css=" + selector;
    }

    abstract protected void defineModule();

    protected void defineUi(String uid, String locator) {
        locatorMap.put(uid, locator);
    }

    protected String uid(String nestedUid) {
        String[] uids = StringUtils.split(nestedUid, ".");

        List<String> locatorParts = new ArrayList<String>();
        if (uids != null) {
            for (String uid : uids) {
                String locator = locatorMap.get(uid);
                locatorParts.add(locator);
            }
        }

        String locator = "css=" + StringUtils.join(locatorParts, " ");
        console.debug("locator->", locator);
        return locator;
    }
}
